import os
from  threading import  Thread, Lock,Condition
from  collections import deque
from time import sleep
import logging

class Player(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.__locker=Lock()
        self.__not_empty=Condition(self.__locker)
        self.__done=Condition(self.__locker)
        self.__tasks=0
        self.__stoped=False
        self.__queue=deque()
        self.start()
    def __qsize(self):
        return len(self.__queue)
    def __pop(self):
        with self.__not_empty:
            while not self.__qsize():
                self.__not_empty.wait()
            return self.__queue.popleft()
    def __palydone(self):
        with self.__locker:
            self.__tasks-=1
            self.__done.notify()
    def run(self):
        while(1):
            fn=self.__pop()
            if fn=='-1':break
            logging.info(f"Playing {fn}")
            os.system(f"mpg123 -q {fn}")
            logging.info(f"Play {fn} done.")
            self.__palydone()
        self.__palydone()
        logging.info("Play all done")
    def play(self,fn):
        with self.__locker:
            if self.__stoped: 
                raise Exception("Player Closed")
            self.__tasks+=1
            self.__queue.append(fn)
            logging.info(f"Start Play {fn}")
            self.__not_empty.notify()
    def stop(self):
        self.play("-1")
        self.waitplay()
        self.join()
    def waitplay(self):
        with self.__done:
            while self.__tasks:
                self.__done.wait()
    def playing(self):
        with self.__locker:
            return self.__tasks>0
